<template>
  <div>
    <div class="page-form">
      <el-select
        v-model="queryParams.status"
        placeholder="处理状态"
        clearable
        @change="handleSearch"
        filterable
      >
        <el-option label="已处理" :value="1" />
        <el-option label="未处理" :value="0" />
      </el-select>
      <el-select
        v-model="queryParams.markerType"
        placeholder="异常类型"
        clearable
        @change="handleSearch"
        filterable
      >
        <el-option
          v-for="dict in dict.type.exception_exam_questions"
          :key="dict.value"
          :label="dict.label"
          :value="dict.value"
        />
      </el-select>
    </div>
    <el-table
      stripe
      border
      ref="tableList"
      v-loading="loading"
      :data="tableData"
      style="width: 100%"
      row-key="id"
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        type="selection"
        width="55"
        align="center"
        :selectable="(e) => e.status !== 1"
        :reserve-selection="true"
      />
      <!-- <el-table-column label="序号" type="index" align="center">
        <template slot-scope="scope">
          <span>{{
            (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1
          }}</span>
        </template>
      </el-table-column> -->
      <!-- <el-table-column
        label="试题密号"
        align="center"
        prop="teacherName"
        :show-overflow-tooltip="true"
      /> -->
      <el-table-column
        label="试题题号"
        align="center"
        prop="questionName"
        :show-overflow-tooltip="true"
      />
      <!-- <el-table-column
        label="角色"
        align="center"
        :show-overflow-tooltip="true"
      >
        <template slot-scope="scope">
          {{ roleFilter(scope.row.role) }}
        </template>
      </el-table-column>
      <el-table-column
        label="手机号&账号"
        align="center"
        prop="phone"
        :show-overflow-tooltip="true"
      /> -->
      <el-table-column
        label="所属学校"
        align="center"
        prop="examSchoolName"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="标记类型"
        align="center"
        prop="markerType"
        :show-overflow-tooltip="true"
      >
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.exception_exam_questions"
            :value="scope.row.markerType"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="标记教师"
        align="center"
        prop="markerTeacherName"
        :show-overflow-tooltip="true"
      /><el-table-column
        label="标记时间"
        align="center"
        prop="markerTime"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="处理状态"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            type="success"
            v-if="scope.row.status == 1"
            size="mini"
            plain
            style="padding: 5px 5px"
            >已处理</el-button
          >
          <el-button
            type="danger"
            v-else-if="scope.row.status == 0"
            size="mini"
            plain
            style="padding: 5px 5px"
            >未处理</el-button
          >
          <el-button
            type="danger"
            v-else-if="scope.row.status == 2"
            size="mini"
            plain
            style="padding: 5px 5px"
            >已报废（题目）</el-button
          >
          <el-button
            type="danger"
            v-else-if="scope.row.status == 3"
            size="mini"
            plain
            style="padding: 5px 5px"
            >已报废（整卷）</el-button
          >
        </template>
      </el-table-column>
      <el-table-column
        v-if="$auth.hasRole('admin')"
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        width="200"
      >
        <template slot-scope="scope">
          <el-link type="primary" @click="processingQuestionCards(scope.row)">{{
            scope.row.status !== 0 ? "查看题卡" : "处理题卡"
          }}</el-link>
          <!-- <el-link type="primary" @click="del(scope.row.id)">查看小图</el-link>
          <el-link type="primary" @click="del(scope.row.id)">答题卡</el-link> -->
          <el-link
            type="danger"
            @click="scrapMethodSub(scope.row)"
            :disabled="scope.row.status !== 0"
            >报废题卡</el-link
          >
          <!-- <el-link type="danger" @click="returnMethodSub(scope.row)" :disabled="scope.row.status !== 0"
            >退回</el-link> -->
        </template>
      </el-table-column>
    </el-table>
    <el-dialog
      title="报废处理"
      :visible.sync="scrapMethodDialogVisible"
      @close="(scrapMethodDialogVisible = false), (scrapMethodData = {})"
    >
      <el-form>
        <el-form-item label="请选择报废方式" label-width="120px">
          <el-radio v-model="scrapMethod" :label="1">此题报废</el-radio>
          <el-radio v-model="scrapMethod" :label="2">整卷报废</el-radio>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button
          @click="(scrapMethodDialogVisible = false), (scrapMethodData = {})"
          >取 消</el-button
        >
        <el-button type="primary" @click="handleScrapSub()">确 定</el-button>
      </div>
    </el-dialog>
    <div class="page-bottom">
      <div class="sel-box">
        <p>
          已选 <span>{{ multipleSelection.length }}</span> 项 / 共
          {{ total }} 项
        </p>
        <el-button
          v-if="$auth.hasRole('admin')"
          type="danger"
          @click="batchScrapMethodSub"
          >批量报废处理</el-button
        >
        <el-button
          type="primary"
          :loading="dcLoading"
          @click="dcycjd"
          >导出异常进度</el-button
        >
      </div>

      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>
  </div>
</template>

<script>
import { debounce } from "lodash";
import {
  examTeacherList,
  examTeacherAdd,
  examTeacherEdit,
  examTeacherDel,
  templatemenu,
  templatemenulist,
} from "@/api/xmgl/pyjsgl";
import {
  getPyxqDetailList,
  getPyxqGroupSelect,
  getSchoolSelect,
  reviewexportexception,
  ycclExceptionList,
  scrapQuestion,
  getIsRated,
  submitResult,
} from "@/api/xmgl/pyjd";
import { schoolsubjectlist, checkPassword } from "@/api/common";
import { teacherlist } from "@/api/jcgl/jsgl";
import { getToken } from "@/utils/auth";
import { scanQuestionCardSchoolListSchool } from "@/api/xmgl/tkcx";
import axios from "axios";
import { schoollist } from "@/api/xmgl/csxx";
import { listRole } from "@/api/system/role";
import { treeselect } from "@/api/system/menu";
import { mount } from "sortablejs";
export default {
  dicts: ["grade", "type", "mode", "exception_exam_questions"],
  props: {
    xmxx: {},
    xmxklb: null,
    subjectId: null,
    subjectName: undefined,
  },
  data() {
    return {
      dcLoading: false,

      scrapMethodDialogVisible: false,
      scrapMethodData: {},
      scrapMethod: undefined,
      multipleSelection: [],

      loading: false,

      ids: [],

      total: 0,
      tableData: [],

      multiple: true,
      typeList: [],
      queryParams: {
        questionName: undefined,
        school: undefined,
        complete: undefined,
        scnTeacher: undefined,
        pageNum: 1,
        pageSize: 15,
      },
      questionList: [],
      schoolList: [],
      editKmVisible: false,
      editForm: {
        addType: "1",
        schoolId: "",
        teacherId: "",
        teacherName: "",
        phone: "",
        password: "",
        role: [],
        reviewSubject: [],
      },
      rules: {
        schoolId: [
          { required: true, message: "学校名称不能为空", trigger: "change" },
        ],
        grade: [{ required: true, message: "年级不能为空", trigger: "change" }],
      },

      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 学校
        deptId: "",
        examSchoolId: "",
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/exam/teacher/import",
      },

      xxlb: [],
      jslb: [],
      roleList: [],
      xklb: [],
      teamList: [],

      qxglVisible: false,
      qxData: [],
    };
  },
  watch: {
    subjectId: {
      handler(newVal, oldVal) {
        if (newVal === "0" && oldVal === undefined) {
          return false;
        }
        if (Number(newVal) && oldVal === "0") {
          this.getList();
        }
        if (Number(newVal) && oldVal === undefined) {
          this.getList();
        }
        if (Number(newVal) && Number(oldVal)) {
          this.getList();
        }
        // if(newVal&&oldVal!=0){
        // }
      },
      deep: true,
    },
  },
  created() {
    if (!this.$auth.hasRole("admin")) {
      scanQuestionCardSchoolListSchool({
        examId: this.xmxx.id,
      }).then((res) => {
        this.queryParams.examSchoolId = res.rows.filter((item) => {
          return this.$store.state.user.deptId == item.schoolId;
        })[0].id;
        this.getList();
      });
    } else {
      this.getList();
    }
  },
  mounted() {},
  methods: {
    // 退回
    returnMethodSub(e) {
      console.log(e);
      let obj = {
        questionId: e.questionId,
        studentId: e.examStudentId,
        examId: this.subjectId,
      };
      submitResult(obj).then((res) => {
        if (res.code === 200) {
          this.$message.success("退回成功");
          e.status = 1;
        }
      });
    },
    scrapMethodSub(e) {
      console.log(e);

      this.scrapMethodData = e;
      this.scrapMethodDialogVisible = true;
    },
    batchScrapMethodSub() {
      if (this.multipleSelection.length === 0) {
        this.$message.warning("请选择要报废的题目");
        return false;
      }
      this.scrapMethodDialogVisible = true;
    },
    // 批量报废处理
    batchHandleScrapSub() {
      if (!this.scrapMethod) {
        this.$message.warning("请选择报废方式");
        return false;
      }
      let obj = [];
      console.log(this.multipleSelection, "this.multipleSelection");

      this.multipleSelection.forEach((item) => {
        console.log(item);

        obj.push({
          studentId: item.examStudentId,
          questionId: item.questionId?item.questionId:item.questionGroupId,
          scrapType: this.scrapMethod, // 此题 1；整卷 2；
          id: item.id,
          templateId: item.examTemplateId,
        });
      });
      getIsRated(obj).then((res) => {
        if (res.data) {
          this.$confirm("题目已存在打分，是否确认报废", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          })
            .then(() => {
              scrapQuestion(obj)
                .then((res) => {
                  if (res.code === 200) {
                    this.$message.success("报废成功");
                    this.getList();
                  }
                })
                .finally(() => {
                  this.scrapMethodDialogVisible = false;
                });
            })
            .catch(() => {
              this.$message({
                type: "info",
                message: "已取消",
              });
            });
        } else {
          scrapQuestion(obj)
            .then((res) => {
              if (res.code === 200) {
                this.$message.success("报废成功");
                this.getList();
              }
            })
            .finally(() => {
              this.scrapMethodDialogVisible = false;
            });
        }
      });
    },
    // 单个报废处理
    handleScrapSub() {
      if (!this.scrapMethod) {
        this.$message.warning("请选择报废方式");
        return false;
      }
      let obj = [];
      if (
        this.multipleSelection.length > 0 &&
        Object.keys(this.scrapMethodData).length === 0
      ) {
        this.multipleSelection.forEach((item) => {
          obj.push({
            studentId: item.examStudentId,
            questionId: item.questionId?item.questionId:item.questionGroupId,
            scrapType: this.scrapMethod, // 此题 1；整卷 2；
            id: item.id,
            templateId: item.examTemplateId,
            examSubjectId: this.subjectId,
          });
        });
      }
      if (Object.keys(this.scrapMethodData).length !== 0) {
        obj.push({
          studentId: this.scrapMethodData.examStudentId,
          questionId: this.scrapMethodData.questionId?this.scrapMethodData.questionId:this.scrapMethodData.questionGroupId,
          scrapType: this.scrapMethod, // 此题 1；整卷 2；
          id: this.scrapMethodData.id,
          templateId: this.scrapMethodData.examTemplateId,
          examSubjectId: this.subjectId,
        });
      }
      console.log("走着扔了");

      getIsRated(obj).then((res) => {
        if (res.data) {
          this.$confirm("题目已存在打分，是否确认报废", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          })
            .then(() => {
              scrapQuestion(obj)
                .then((res) => {
                  if (res.code === 200) {
                    this.$message.success("报废成功");
                    this.getList();
                  }
                })
                .finally(() => {
                  this.scrapMethodDialogVisible = false;
                });
            })
            .catch(() => {
              this.$message({
                type: "info",
                message: "已取消",
              });
            });
        } else {
          scrapQuestion(obj)
            .then((res) => {
              if (res.code === 200) {
                this.$message.success("报废成功");
                this.getList();
              }
            })
            .finally(() => {
              this.scrapMethodDialogVisible = false;
            });
        }
      });
    },
    getList() {
      this.loading = true;
      this.tableData = [];
      // this.$refs.tableList.clearSelection();
      let obj = {
        ...this.queryParams,
      };
      ycclExceptionList(obj, this.subjectId)
        .then((response) => {
          this.tableData = response.rows;
          this.total = response.total;
        })
        .finally(() => {
          this.loading = false;
        });
    },
    // 获取 题组-学校：下拉框列表
    // getSelectList(){
    //   this.dict.type.exception_exam_questions
    // },
    handleSelectionChange(selection) {
      console.log(selection, "selection");

      this.multipleSelection = selection;
      this.multiple = !selection.length;
    },
    debouncedSearch: debounce(function () {
      this.queryParams.pageNum = 1;
      this.getList();
    }, 800),
    // 搜索条件
    handleSearch() {
      this.debouncedSearch();
    },
    processingQuestionCards(e) {
      this.$router.push({
        path: "/processingquestioncards/index",
        query: {
          type: e.status !== 0 ? "detail" : "list",
          //   id: e.id,
          //   subjectId: this.subjectId,
        },
      });
      sessionStorage.setItem(
        "ycclId",
        JSON.stringify({
          id: e.id,
          examStudentId: e.examStudentId,
          subjectId: this.subjectId,
        })
      );
    },
    // 导出进度
    async dcycjd() {
      this.dcLoading = true;
      await reviewexportexception({
        examIdMainId: this.xmxx.id,
      })
        .then((res) => {
          // 创建临时链接
          const blob = new Blob([res.data]);
          if (blob.size == 0) {
            this.$modal.alert("当前暂无数据，无法导出");
            return;
          }
          // this.$download.saveAs(blob, `${this.subjectName}_评阅进度_${new Date().getTime()}.xlsx`);
          // 创建临时链接
          const link = document.createElement("a");
          link.href = window.URL.createObjectURL(blob);
          link.download = `${
            this.xmxx.examName
          }_异常未处理_${new Date().getTime()}.xlsx`;
          link.style.display = "none";
          console.log(
            window.URL.createObjectURL(blob),
            "window.URL.createObjectURL(blob)"
          );

          // 触发下载
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
          window.URL.revokeObjectURL(link.href);

          this.$message.success("导出成功");
        })
        .finally(() => {
          this.dcLoading = false;
        });
      // return new Promise((resolve, reject) => {
      //   axios({
      //   method: 'get',
      //   url: '/task/teacher/stats/review/export',
      //   responseType: 'blob',
      //   headers: { 'Authorization': 'Bearer ' + getToken() }
      // }).then((res) => {
      //   const isBlob = blobValidate(res.data);
      //   if (isBlob) {
      //     const blob = new Blob([res.data])
      //     saveAs(blob,`${this.subjectName}_评阅进度_${new Date().getTime()}.xlsx`)
      //   } else {
      //     this.printErrMsg(res.data);
      //   }
      // })
      // });
      return;
      try {
        const res = await reviewexportexception(
          { ...this.queryParams, examSubjectId: this.subjectId },
          {
            responseType: "blob", // 必须指定响应类型
          }
        );
        // 创建临时链接
        const blob = new Blob([res.data]);
        const downloadUrl = window.URL.createObjectURL(blob);
        console.log(downloadUrl, "downloadUrl");

        // 从headers获取文件名
        // const fileName = decodeURIComponent(
        //   res.headers['content-disposition']
        //     .split('filename=')[1]
        //     .replace(/"/g, '')
        // ) || `${this.xmxx.name}_评阅进度_${new Date().getTime()}.xlsx`
        console.log(this.subjectName);

        const fileName = `${
          this.subjectName
        }_评阅进度_${new Date().getTime()}.xlsx`;
        // 创建隐藏的a标签触发下载
        const link = document.createElement("a");
        link.href = downloadUrl;
        link.download = fileName;
        link.style.display = "none";
        document.body.appendChild(link);
        link.click();
        // 清理资源
        window.URL.revokeObjectURL(downloadUrl);
        document.body.removeChild(link);
        this.$message.success("文件下载成功");
      } catch (error) {
        console.log(error, "error");
        this.$message.error("文件下载失败");
        return false;
      }
    },
    async printErrMsg(data) {
      const resText = await data.text();
      const rspObj = JSON.parse(resText);
      const errMsg =
        errorCode[rspObj.code] || rspObj.msg || errorCode["default"];
      Message.error(errMsg);
    },
    blobValidate(data) {
      return data.type !== "application/json";
    },

    beforeClose(done) {
      this.editForm = {
        addType: "1",
        schoolId: "",
        teacherId: "",
        teacherName: "",
        phone: "",
        password: "",
        role: [],
        reviewSubject: [],
      };
      this.bjlb = [];
      this.xslb = [];
      this.$nextTick(() => {
        this.$refs.editForm.clearValidate();
        done();
      });
    },
    handleClose() {
      this.beforeClose(() => {
        this.editKmVisible = false;
      });
    },

    editSubmit() {
      this.$refs.editForm.validate((valid) => {
        if (valid) {
          this.loading = true;
          let req;
          if (this.editForm.id) {
            req = examTeacherEdit;
          } else {
            req = examTeacherAdd;
          }
          let data = {
            ...this.editForm,
            examId: this.xmxx.id,
          };

          data.schoolId = this.xxlb.filter((item) => {
            return item.schoolId == data.schoolId;
          })[0].id;
          data.role = data.role.join(",");
          data.reviewSubject = data.reviewSubject.join(",");

          if (data.addType == "1") {
            data.teacherName = this.jslb.filter((item) => {
              return item.userId == data.teacherId;
            })[0].nickName;
          }

          req(data)
            .then((res) => {
              this.$modal.msgSuccess("操作成功");
              this.handleClose();
              this.getList();
            })
            .finally(() => {
              this.loading = false;
            });
        }
      });
    },
    del(id) {
      this.$prompt(
        "删除考生后，可能造成考生数据异常情况，请输入管理员密码以进行下步操作!",
        "刪除考生",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          inputPlaceholder: "请输入管理员密码",
          inputType: "password",
          inputValidator: (value) => {
            if (!value) {
              return "请输入密码";
            } else {
              return true;
            }
          },
        }
      )
        .then(({ value }) => {
          checkPassword({
            password: value,
            schoolId: this.$store.state.user.deptId,
          }).then((res) => {
            examTeacherDel(id ? id : this.ids).then((res) => {
              this.$modal.msgSuccess("操作成功");
              this.$refs.tableList.clearSelection();
              this.ids = [];
              this.getList();
            });
          });
        })
        .catch(() => {});
    },

    handleImport() {
      this.upload.title = "用户导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download(
        "/system/exam/teacher/import",
        {},
        `user_template_${new Date().getTime()}.xlsx`
      );
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.deptId = "";
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(
        "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
          response.msg +
          "</div>",
        "导入结果",
        { dangerouslyUseHTMLString: true }
      );
      this.allDeptList = null;
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      if (!this.upload.deptId) {
        this.$modal.alertError("请选择导入学校");
        return;
      }
      this.$refs.upload.submit();
    },

    addTypeChange(value) {
      this.editForm = {
        addType: value,
        schoolId: "",
        teacherId: "",
        teacherName: "",
        phone: "",
        password: "",
        role: [],
        reviewSubject: [],
      };
      this.xklb = [];

      this.$nextTick(() => {
        this.$refs.editForm.clearValidate();
      });
    },
    schoolChange() {
      this.editForm.classId = "";
      this.editForm.studentId = "";

      teacherlist({
        pageNum: 1,
        pageSize: 9999,
        deptId: this.editForm.schoolId,
      }).then((res) => {
        this.jslb = res.rows;
      });

      let examSchoolId = this.xxlb.filter((item) => {
        return item.schoolId == this.editForm.schoolId;
      })[0].id;
      schoolsubjectlist({
        examId: this.xmxx.id,
        examSchoolId: examSchoolId,
      }).then((res) => {
        this.xklb = res.rows;
      });
    },

    teacherChange() {
      let teacher = this.jslb.filter((item) => {
        return item.userId == this.editForm.teacherId;
      })[0];

      this.editForm.password = teacher.password;
      this.editForm.phone = teacher.userName;
      this.editForm.role = teacher.userRoleVoList.map((item) => {
        return item.roleName;
      });
      this.editForm.reviewSubject = teacher.reviewSubject;
    },
    getExamSchoolId(value) {
      this.upload.examSchoolId = this.xxlb.filter((item) => {
        return item.schoolId == value;
      })[0].id;
    },

    roleFilter(role) {
      let roleArr = role.split(",");
      return this.roleList
        .filter((item) => {
          return roleArr.indexOf(item.roleId.toString()) != -1;
        })
        .map((item) => {
          return item.roleName;
        })
        .join(",");
    },

    qxopen() {
      this.loading = true;
      templatemenulist({ examId: this.xmxx.id })
        .then((res) => {
          this.qxglVisible = true;
          let qxData = JSON.parse(JSON.stringify(this.qxData));

          qxData.map((item) => {
            res.rows.map((v) => {
              if (item.roleId == v.roleId) {
                item.checked.push(v.menuId);
              }
            });
          });

          this.qxData = qxData;
        })
        .finally(() => {
          this.loading = false;
        });
    },

    qxglbc() {
      this.loading = true;

      let arr = this.qxData.filter((item) => {
        return item.checked && item.checked.length > 0;
      });

      let data = [];
      arr.map((item) => {
        item.checked.map((v) => {
          data.push({
            roleId: item.roleId,
            menuId: v,
            examId: this.xmxx.id,
          });
        });
      });

      templatemenu(data)
        .then((res) => {
          this.qxglVisible = false;
          this.$modal.msgSuccess("操作成功");
        })
        .finally(() => {
          this.loading = true;
        });
    },
  },
};
</script>

<style lang="scss" scoped>
.editKmVisible {
  .el-input,
  .el-cascader,
  .el-select {
    width: 240px;
  }
}
</style>